#include "../include/client_func.h"
#include "../include/ftp_func.h"



int tcp_client_init()
{
    strcpy(tcp_ip, "192.168.149.128");
    strcpy(tcp_port, "2000");

    // 1. 生成套接字描述符
    sfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(sfd, -1, "socket");

    struct sockaddr_in ser_addr; // 服务器信息结构体
    bzero(&ser_addr, sizeof(ser_addr));
    ser_addr.sin_family = AF_INET; // 使用IPv4
    ser_addr.sin_port = htons(atoi(tcp_port)); // 端口号
    ser_addr.sin_addr.s_addr = inet_addr(tcp_ip); // IP地址

    // 2. connect
    ret = connect(sfd, (struct sockaddr *)&ser_addr, sizeof(ser_addr));
    ERROR_CHECK(ret, -1, "connect");

    is_running = 1;
}

int start()
{
    while(is_running)
    {
        memset(&t_data, 0, sizeof(t_data));

        fgets(t_data.buf, 128, stdin);
        t_data.buf[strlen(t_data.buf) - 1] = '\0';

        if (!strncmp(t_data.buf, "cd", 2))
        {
            do_cd(t_data);
        }
        else if(!strncmp(t_data.buf, "ls", 2))
        {
            do_ls(t_data);
        }
        else if (!strncmp(t_data.buf, "puts", 4))
        {
            do_puts(t_data);
        }
        else if (!strncmp(t_data.buf, "gets", 4))
        {
            do_gets(t_data);
        }
        else if(!strncmp(t_data.buf, "remove", 6))
        {
            do_remove(t_data);
        }
        else if(!strcmp(t_data.buf, "pwd"))
        {
            do_pwd(t_data);
        }
        else
        {
            do_default(t_data);
        }
    }
    close(sfd);
}

int do_cd()
{
    send(sfd, &t_data, sizeof(t_data), 0);

    // system("clear");
    memset(&r_data, 0, sizeof(r_data));
    recv(sfd, &r_data, sizeof(r_data), 0);
    printf("%s\n", r_data.buf);

    return 0;
}

int do_ls()
{
    send(sfd, &t_data, sizeof(t_data), 0);

    system("clear");
    memset(&r_data, 0, sizeof(r_data));
    recv(sfd, &r_data, sizeof(r_data), 0);
    printf("%s\n", r_data.buf);
    
    return 0;
}

int do_puts()
{
    struct stat buf;
    ret = stat(t_data.buf + 5, &buf);

    if (S_ISDIR(buf.st_mode) || ret == -1)
    {
        printf("can not put folder");
        return -1;
    }
    else
    {
        send_n(sfd, &t_data, sizeof(t_data));

        upload_file(sfd, t_data.buf + 5);
        
        return 0;
    }
}

int do_gets()
{
    send(sfd, &t_data, sizeof(t_data), 0);

    recv(sfd, &r_data, sizeof(t_data), 0);

    if (r_data.data_len)
    {
        download_file(sfd);
    }
    else
    {
        printf("%s\n", r_data.buf);
    }

    return 0;
}

int do_remove()
{
    send_n(sfd, &t_data, sizeof(t_data));

    memset(&r_data, 0, sizeof(r_data));
    recv(sfd, &r_data, sizeof(r_data), 0);
    printf("%s\n", r_data.buf);
    
    return 0;
}

int do_pwd()
{
    send_n(sfd, &t_data, sizeof(t_data));

    memset(&r_data, 0, sizeof(r_data));
    recv(sfd, &r_data, sizeof(r_data), 0);
    printf("%s\n", r_data.buf);
    
    return 0;
}

int do_default()
{
    printf("wrong command");
    return 0;
}